import React, { Component, Fragment } from "react";
// antd
import { Table, Button, Col, Pagination, Form, Input, message, Select} from "antd";
// http
import http from '../../../utils/request';

const { Option } = Select;

class CloudAccountLogManage extends Component {
    constructor(props){
        super(props);
        this.state = {
            // 表格分页
            total: '',
            page: 1,
            page_number: 10,
            dataSource: [],
            columns: [
                {title: "类别", dataIndex: "types", key: "types"},
                {title: "云平台", dataIndex: "platform", key: "platform"},
                {title: "云账户", dataIndex: "name", key: "name"},
                {title: "用户", dataIndex: "user", key: "user"},
                {title: "时间", dataIndex: "created", key: "created"}
            ],
            loading: false,
            visible_add: false,     // 添加
            visible_edit: false,    // 编辑
            visible_key_edit: false,
            visible_change_tag: false,
            visible_delete: false,  // 删除
            visible_grant: false,   // 账户授权
            change_account_list: '',    // 批量替换标签展示
            visible_edit_id: '',
            visible_edit_name: '',
            visable_edit_code: '',
            cloud_account_id: '',
            cloud_account_name: '',
            cloud_account_tag: [''],
            search_cloud_platform: null,
            search_cloud_name: null,
            search_cloud_user: null,
            search_cloud_types: null,
            search_option_account: [],
            platform_list_option: [],
            region_list_option: [],
            selectedRowKeys: [],
        }
        this.formRefAdd = React.createRef();
        this.formRefEdit = React.createRef();
        this.formRefMsg = React.createRef();
        this.formRefKeyEdit = React.createRef();
        this.formRefChangeTag = React.createRef();
        this.formRefGrant = React.createRef();
    }

    componentDidMount() {
        this.loadData()
        this.loadDataCloudPlatform()
    }

    loadDataCloudPlatform = () => {
        // 获取云平台列表
        const requestData = {
            'page': 1,
            'limit': 1000,
        }
        http.get('/cloud/platform', {params: requestData}).then(response=> {
            const resp_data = response.data.data.items
            
            const platform_list_option = []
            for (let i = 0; i < resp_data.length; i++) {
                platform_list_option.push(<Option key={resp_data[i].name}>{resp_data[i].name}</Option>)
            }
            this.setState({
                platform_list_option: platform_list_option,
            })
        })
    }

    loadData = () => {
        this.setState({
            loading: true
        })
        
        const requestData = {
            'page': this.state.page,
            'limit': this.state.page_number,
            'platform__contains': this.state.search_cloud_platform,
            'name__contains': this.state.search_cloud_name,
            'user__contains': this.state.search_cloud_user,
            'types': this.state.search_cloud_types,
        }
        // 获取云账户列表
        http.get('/cloud/account/log', {params: requestData}).then(response=>{
            this.setState({
                dataSource: response.data.data.items,
                total: response.data.data.pages.total,
                loading: false
            })
        }).catch()
    }

    /** 切换每页数量 */
    onChangeSizePage = (page, page_number) => {
        this.setState({
            page: page,
            page_number: page_number,
        }, () => {
            this.loadData()
        })
    }

    /** 云平台搜索 */
    onFinishSearch = (data) => {
        this.setState({
            page: 1,
            search_cloud_name: data.name ? data.name : '',
            search_cloud_platform: data.platform ? data.platform : '',
            search_cloud_user: data.user ? data.user : '',
            search_cloud_types: data.types ? data.types : null,
        })
        this.loadData()
    }

    // 搜索云账户
    onChangeAccountName = (value) => {
        this.setState({
            search_cloud_name: value ? value : null
        })
    }

    // 搜索切换云平台
    onChangePlatform = (value) => {
        if (value) {
            this.setState({
                search_cloud_account_name: value
            })
            const requestData = {
                'page': 1,
                'limit': 1000,
                'platform': value
            }
    
            http.get('/cloud/account', {params: requestData}).then(response=>{
                const search_option_account = []
                const resp_data = response.data.data.items
                for (let i = 0; i < resp_data.length; i++) {
                    search_option_account.push(<Option key={resp_data[i].name}>{resp_data[i].name}</Option>)
                }
                this.setState({
                    search_option_account: search_option_account
                })
            })
        } else {
            this.setState({
                search_cloud_account_name: ''
            })            
        }
    }


    // 根据云平台选择云区域
    changeCloudPlatform = (value) => {
        const requestData = {
            'page': 1,
            'limit': 1000,
            'platform': value,
        }

        // 获取云账户列表
        http.get('/cloud/region', {params: requestData}).then(response=>{
            const resp_data = response.data.data.items
            const region_list_option = []
            for (let i=0; i < resp_data.length; i++) {
                region_list_option.push(<Option key={resp_data[i].code}>{resp_data[i].name}</Option>)
            }

            this.setState({
                region_list_option: region_list_option
            })
        }).catch()
    }

    // 批量选中标签
    onSelectChange = (selectedRowKeys) => {
        this.setState({
            selectedRowKeys: selectedRowKeys
        })
    }

    // 修改资源巡检状态
    onChangeCmsMonitorStatus = (id) => {
        this.setState({
            loading: true
        })
        const requestData = {
            id: id,
            types: 'change_cms_monitor_status',
        }
        http.patch('/cloud/account/' + id, requestData).then(response=>{
            message.success(response.data.msg)
            this.setState({
                loading: false
            })
            this.loadData()
        }).catch()
    }

    // 授权按钮
    onGrantAuthorizationBtn = (rowData) => {
        this.setState({
            visible_grant: true
        })
        http.get('/cloud/account').then(response=> {
            this.formRefGrant.current.setFieldsValue({
                id: rowData.id,
                authorization_data: rowData.authorization_data,
            })
        })
    }

    // 授权取消
    onFinishGrantAuthorizationCancel = () => {
        this.setState({
            visible_grant: false
        })
        this.formRefGrant.current.resetFields()
    }

    // 授权提交
    onFinishGrantAuthorization = (data) => {
        this.setState({
            loading: true
        })
        const requestData = {
            id: data.id,
            types: 'grant_authorization',
            authorization_data: data.authorization_data
        }
        http.patch('/cloud/account/' + data.id, requestData).then(response=>{
            message.success(response.data.msg)
            this.setState({
                loading: false,
                visible_grant: false,
            })
            this.loadData()
        }).catch()
    }

    render(){
        const { loading, dataSource, columns, page, total,search_option_account,
              platform_list_option, selectedRowKeys } = this.state
        const rowSelection = {
            selectedRowKeys,
            onChange: this.onSelectChange,
        }
        var myStyle = {margin: '20px'}
        var myStyle1 = {margin: '10px', float: 'right'}
        return (
            <Fragment>
                <Form layout="inline" onFinish={this.onFinishSearch}>

                    <Form.Item label="云平台" name="platform">
                        <Select
                            allowClear
                            showSearch
                            style={{ width: 200 }}
                            placeholder="请选择平台"
                            optionFilterProp="children"
                            onChange={this.onChangePlatform}
                            filterOption={(input, option) =>
                            option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                        >
                            {platform_list_option}
                        </Select>
                    </Form.Item>

                    <Form.Item label="云账户" name="name">
                        <Select
                            allowClear
                            showSearch
                            style={{ width: 180 }}
                            placeholder="请选择云账户"
                            onChange={this.onChangeAccountName}
                            >
                            {search_option_account}
                        </Select>                      
                    </Form.Item>

                    <Form.Item label="查询用户" name="user">
                        <Input placeholder="请输入用户名"  />
                    </Form.Item>

                    <Form.Item label="类别" name="types">
                        <Select
                            allowClear
                            showSearch
                            style={{ width: 180 }}
                            placeholder="请选择类别"
                            >
                            <Option key="查询">查询</Option>
                            <Option key="授权">授权</Option>
                        </Select>                      
                    </Form.Item>

                    <Form.Item shouldUpdate={true}>
                        <Button type="primary" htmlType="submit">搜索</Button>
                    </Form.Item>
                </Form>

                <div style={myStyle1}>
                </div>
                
                <Table
                    pagination={false} 
                    rowSelection={rowSelection} 
                    rowKey="id" 
                    columns={columns} 
                    dataSource={dataSource}
                    loading={loading}
                    scroll={{ y: 500, x: '70vw' }}
                >
                </Table>

                <div style={myStyle}>
                    <Col span={16}>
                        <Pagination
                            onChange={this.onChangeSizePage}
                            current={page}
                            total={total}
                            showSizeChanger
                            showQuickJumper
                            showTotal={total => `Total ${total} items`}
                        />
                    </Col>
                </div>
            </Fragment>
        )
    }
}
export default CloudAccountLogManage;